<template>
  <div class="p-2">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="流程标识" class="smart-query-form-item">
          <a-input v-model:value="queryParams.processKey" placeholder="请输入流程标识" />
        </a-form-item>
        <a-form-item label="流程名称" class="smart-query-form-item">
          <a-input v-model:value="queryParams.processName" placeholder="请输入流程名称" />
        </a-form-item>
        <a-form-item label="流程分类" class="smart-query-form-item">
          <a-select v-model:value="queryParams.category" placeholder="流程分类" style="width: 220px">
            <a-select-option v-for="item in categoryOptions" :key="item.categoryId" :value="item.code">
              {{ item.categoryName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态" class="smart-query-form-item">
          <a-select v-model:value="queryParams.state" placeholder="请选择状态">
            <a-select-option value="active">激活</a-select-option>
            <a-select-option value="suspended">挂起</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item smart-margin-left10">
          <a-button-group>
            <a-button type="primary" @click="handleQuery"> <SearchOutlined />搜索 </a-button>
            <a-button @click="resetQuery"> <ReloadOutlined />重置 </a-button>
          </a-button-group>
        </a-form-item>
      </a-row>
    </a-form>

    <a-card size="small" :bordered="false">
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button danger @click="handleDelete()" :disabled="multiple"> <DeleteOutlined />删除 </a-button>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </div>
      </a-row>

      <a-table :columns="columns" :dataSource="deployList" :loading="loading" :pagination="false" bordered :row-selection="rowSelection">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'version'">
            <a-tag>v{{ record.version }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="record.suspended ? 'orange' : 'green'">
              {{ record.suspended ? '挂起' : '激活' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button type="link" @click="handlePublish(record)">
              <template #icon>
                <BranchesOutlined />
              </template>
              版本管理
            </a-button>

            <a-button type="link" danger @click="handleDelete(record)">
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
          </template>
        </template>
      </a-table>

      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          :total="total"
          v-model:current="queryParams.pageNum"
          v-model:pageSize="queryParams.pageSize"
          @change="getList"
        />
      </div>
    </a-card>

    <!-- 版本管理对话框 -->
    <a-modal v-model:open="publishDialog.visible" title="版本管理" width="50%" :footer="null">
      <a-table :columns="publishColumns" :dataSource="publishList" :loading="publishLoading" :scroll="{ x: 800 }" :pagination="false" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <a-button type="link" @click="handleChangeState(record, 'suspended')"> 挂起 </a-button>
            <a-button type="link" @click="handleChangeState(record, 'active')"> 激活 </a-button>
            <a-button type="link" danger @click="handleDelete(record)"> 删除 </a-button>
          </template>
        </template>
      </a-table>
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          :total="publishTotal"
          v-model:current="publishParams.pageNum"
          v-model:pageSize="publishParams.pageSize"
          @change="getPublishList"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup name="Deploy">
  import { categoryApi } from '/@/api/workflow/category';
  import { deployApi } from '/@/api/workflow/deploy';
  import { message, Modal } from 'ant-design-vue';

  const { proxy } = getCurrentInstance();

  const categoryOptions = ref([]);

  const deployList = ref([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const publishList = ref([]);
  const publishLoading = ref(true);
  const publishTotal = ref(0);

  const queryFormRef = ref(null);
  const processDialog = reactive({
    visible: false,
    title: '',
  });
  const publishDialog = reactive({
    visible: false,
    title: '',
  });
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      processKey: '',
      processName: undefined,
      category: undefined,
    },
    publishParams: {
      pageNum: 1,
      pageSize: 10,
      processKey: '',
    },
    rules: {},
  });
  const rowSelection = ref({
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  });

  const queryParams = computed(() => data.queryParams);
  const publishParams = computed(() => data.publishParams);

  /** 查询流程分类列表 */
  const getCategoryList = async () => {
    const res = await categoryApi.listAllCategory();
    categoryOptions.value = res.data;
  };

  const getList = async () => {
    loading.value = true;
    const { data } = await deployApi.listDeploy(queryParams.value);
    deployList.value = data.list;
    total.value = data.total;
    loading.value = false;
  };
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  };
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields();
    handleQuery();
  };
  /** 多选框选中数据 */
  const handleSelectionChange = (selection) => {
    ids.value = selection.map((item) => item.deploymentId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  };
  /** 删除按钮操作 */
  const handleDelete = async (row) => {
    const deploymentIds = row?.deploymentId || ids.value;
    Modal.confirm({
      title: '确认删除',
      content: `是否确认删除参数编号为"${deploymentIds}"的数据项？`,
      onOk: async () => {
        await deployApi.delDeploy(deploymentIds);
        getList();
        message.success('删除成功');
      },
    });
  };
  const getPublishList = async () => {
    publishLoading.value = true;
    const { data } = await deployApi.listPublish(publishParams.value);
    publishList.value = data.list;
    publishTotal.value = data.total;
    publishLoading.value = false;
  };
  const handlePublish = (row) => {
    publishParams.value.processKey = row.processKey;
    publishDialog.visible = true;
    getPublishList();
  };
  const handleProcessView = (row) => {};
  const handleChangeState = async (row, state) => {
    const params = {
      definitionId: row.definitionId,
      state: state,
    };
    await changeState(params);
    message.success('操作成功');
    getPublishList();
  };

  const categoryFormat = (row) => {
    return categoryOptions.value.find((k) => k.code === row.category)?.categoryName ?? '';
  };

  const columns = ref([
    {
      title: '流程标识',
      dataIndex: 'processKey',
      ellipsis: true,
    },
    {
      title: '流程名称',
      dataIndex: 'processName',
      ellipsis: true,
    },
    {
      title: '流程分类',
      dataIndex: 'category',
      customRender: ({ record }) => {
        return categoryFormat(record);
      },
    },
    {
      title: '流程版本',
      dataIndex: 'version',
    },
    {
      title: '状态',
      dataIndex: 'status',
    },
    {
      title: '部署时间',
      dataIndex: 'deploymentTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 280,
    },
  ]);

  const publishColumns = ref([
    {
      title: '流程标识',
      dataIndex: 'processKey',
      ellipsis: true,
    },
    {
      title: '流程名称',
      dataIndex: 'processName',
      ellipsis: true,
    },
    {
      title: '流程版本',
      dataIndex: 'version',
    },
    {
      title: '状态',
      dataIndex: 'status',
      customRender: ({ record }) => {
        return record.suspended ? '挂起' : '激活';
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 300,
    },
  ]);

  onMounted(() => {
    getCategoryList();
    getList();
  });
</script>
